package com.smartsoft.fragment;

import android.app.Activity;
import android.app.Fragment;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.*;
import android.widget.Button;
import android.widget.VideoView;
import com.smartsoft.R;
import com.smartsoft.service.DataManager;

public class VideoFragment extends Fragment {

    /**
     * For debug purposes.
     */
    private static final String TAG = VideoFragment.class.getName();
    /**
     * Callback container for Add Contact handling.
     */
    private OnAddContactListener mAddContactHandler;

    /**
     * Activity have to implements this method in order to be notified
     * when user presses Add Contact button.
     */
    public interface OnAddContactListener {
        /**
         * This callback method will be called on the container (activity)
         * when user presses Add Contact button.
         */
        public void onContactAddition();
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (!(activity instanceof OnAddContactListener)) {
            throw new ClassCastException(activity + " have to implements OnAddContactListener interface");
        }
        mAddContactHandler = (OnAddContactListener) activity;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View videoFragmentView = inflater.inflate(R.layout.video_fragment, container);

        // Video player initialization
        final VideoView mVideoView = (VideoView) videoFragmentView.findViewById(R.id.video_view);
        mVideoView.setVideoURI(DataManager.getResourceUri(R.raw.matrix, getActivity().getPackageName()));
        mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                if (!mVideoView.isPlaying()) {
                    mVideoView.start();
                }
            }
        });
        mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mVideoView.start();
            }
        });

        // Propagate Add Contact handling to the fragment's container (activity)
        Button mAddContact = (Button) videoFragmentView.findViewById(R.id.add_contact_btn);
        mAddContact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mAddContactHandler.onContactAddition();
            }
        });

        return videoFragmentView;
    }

}